<template>
  <n-button type="primary" text :disabled="disabledButtonCode" @click="handleFetchCode">
    {{ smsCodeText }}
  </n-button>

  <x-verify ref="verify" :v-space="15" @success="success"></x-verify>
</template>

<script setup lang="ts">
  import { NButton } from 'naive-ui'
  import { useStore } from '@/store'
  import { XVerify } from '@/components/x-verifition/index'
  import { computed, ref } from 'vue'
  const props = defineProps({
    mobile: {
      type: String,
      default: ''
    },
    smsType: String
  })
  const store = useStore()
  const countDownTime = ref(0)
  const smsCodeText = computed(() => {
    let text = '获取验证码'
    if (countDownTime.value > 0) {
      text = `重新获取 ${countDownTime.value}秒`
    }
    return text
  })
  const disabledButtonCode = computed(() => {
    const isMobile = /^1[3-9]\d{9}$/g.test(props.mobile)
    return !(isMobile && countDownTime.value === 0)
  })

  const handleFetchCode = () => {
    showCode()
  }

  function timer() {
    setTimeout(() => {
      countDownTime.value--
      if (countDownTime.value > 0) {
        timer()
      } else {
      }
    }, 1000)
  }

  const verify = ref(null)
  function showCode() {
    verify.value.show()
  }
  const success = (res) => {
    smsCode(res)
  }
  async function smsCode(res) {
    await store.dispatch('user/getSmsCode', {
      captchaVerification: res.captchaVerification || '',
      mobile: props.mobile,
      smsType: props.smsType
    })
    countDownTime.value = 60
    timer()
  }
</script>

<style scoped lang="scss"></style>
